package com.huitong.common.json.config;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.huitong.common.json.handler.NumberSerializerHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * Jackson配置
 *
 * @author fromdrowning
 * @date 2024/3/17 15:44
 */
@Slf4j
@AutoConfiguration(before = JacksonAutoConfiguration.class)
public class JacksonConfiguration {

    /**
     * 全局序列化处理配置
     *
     * @return 全局序列化处理器
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return builder -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            javaTimeModule.addSerializer(Long.class, NumberSerializerHandler.NUMBER_SERIALIZER_HANDLER)
                .addSerializer(Long.TYPE, NumberSerializerHandler.NUMBER_SERIALIZER_HANDLER)
                .addSerializer(BigInteger.class, NumberSerializerHandler.NUMBER_SERIALIZER_HANDLER)
                .addSerializer(BigDecimal.class, ToStringSerializer.instance)
                .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter))
                .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));

            builder.modules(javaTimeModule)
                .timeZone(TimeZone.getDefault());

            log.info("初始化Jackson配置完成");
        };
    }
}
